package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSON;
import com.lance.answer.gui.answer.gk.answer.lms.LmsOuchnVideoInfo.*;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.util.HttpUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>学生点击所有的连接<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class TestYiWangYiSaveVideoAll {


    public static void main(String[] args) throws Exception {
        String driverPath = "c:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
        driver.get(url);
        Thread.sleep(3000);


        String userName = "1942001212871";
        String pwd = "Ouchn@2021";

        String subjectName = "习近平新时代中国特色社会主义思想";

        WebElement userNameInput = driver.findElement(By.id("loginName"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);
        //TimeUnit.SECONDS.sleep(1);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码
        Thread.sleep(10000);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();

        Thread.sleep(10000);

        // 在题库里获取答案

    //    String courseId = "14182";
        String courseId = "14192";


        // Fixme 点击播放视频 到底需不需要点击？?可能点击还影响了看下一章节
        //  driver.findElement(By.cssSelector("button[class='mvp-toggle-play mvp-first-btn-margin']")).click();


        // https://lms.ouchn.cn/course/14192/ng#/courseware 所有视频list
        boolean loop = true;
        while (loop) {

            LmsOuchnVideoInfo lmsOuchnVideoInfo = getUserCourseInfo(driver, courseId);
            List<ActivityReadsDTO> activityReads = lmsOuchnVideoInfo.getActivityReads();
            Collections.sort(activityReads);
            loop = false;
            for (LmsOuchnVideoInfo.ActivityReadsDTO activityReadsDTO : activityReads) {
                if (!activityReadsDTO.getActivityType().equals("learning_activity")) {
                    continue;
                }
                if (activityReadsDTO.getCompleteness().equals("full")) {
                    continue;
                }
                loop = true;
                break;
            }
            for (LmsOuchnVideoInfo.ActivityReadsDTO activityReadsDTO : activityReads) {
                // 这里的loop判断好像是有点问题的
                if (!activityReadsDTO.getActivityType().equals("learning_activity")) {
                    continue;
                }
                if (activityReadsDTO.getCompleteness().equals("full")) {
                    continue;
                }

                int videoId = activityReadsDTO.getActivityId();

                /**
                 *  FIXME 补刷每个视频的时候，先点击到当前页面，判断该页面是否有视频，如果有视频就POST SAVE视频进度，当所有的视频进度SAVE完之后，休眠30S然后重新获取
                 */

                System.out.println(JSON.toJSONString(activityReadsDTO));
                driver.get("https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen#/" + videoId);

                Thread.sleep(10000);

                String timeString = "";
                WebElement timeWe = Util.findByCssSelector(driver, "*[class='duration']");
                // 为空说明没有可观看视频的了
                if (null == timeWe) {
                    continue;
                }
                timeString = findElementByCssSelector(driver, "*[class='duration']", 30).getText();
                System.err.println("timeString:" + timeString);
                int videoLength = getTime(timeString);
                // cookie 一一定要保持cookie是最新的！
                saveVideoInfo(courseId, String.valueOf(videoId), videoLength, Util.getCookie(driver.manage().getCookies()));
                Thread.sleep(60 * 1000);
            }

        }


        System.err.println("end...............");
        // fixme  4-19 现在的思路是想办法拿到所有的课程ID  1、通过程序获取，最智能   2、手动获取，最傻瓜

        Thread.sleep(2000000);


//
    }

    public static LmsOuchnVideoInfo getUserCourseInfo(WebDriver driver, String courseId) throws Exception {

        String courseUrl = "https://lms.ouchn.cn/course/" + courseId + "/ng#/";
        driver.get(courseUrl);

        Thread.sleep(10000);
        String cookie = Util.getCookie(driver.manage().getCookies());

        String getUrl = "https://lms.ouchn.cn/api/course/"+courseId+"/activity-reads-for-user";

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/" + courseId + "/activity-reads-for-user");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        return JSON.parseObject(result, LmsOuchnVideoInfo.class);
    }


    public static void saveVideoInfo(String courseId, String videoId, int videoLength, String cookie) throws Exception {

        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/" + videoId;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen");
        heads.put(":method", "POST");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("origin", "https://lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/activities-read/" + videoId);

        // Map<String,Object> data   = Maps.newHashMap();
        JSONObject saveJson = new JSONObject();
        // 课程ID，固定的
        //   int videoLength = 449;

        int defaultStep = 60;
        int end = 0;
        while (end < videoLength) {
            saveJson.clear();
            saveJson.put("start", end);
            saveJson.put("end", Math.min((end + defaultStep), videoLength));
            String result = HttpUtil.postJson(postUrl, saveJson, cookie, heads);
            System.err.println(result);
            YiWangYiVideoReturnInfo returnInfo = JSON.parseObject(result, YiWangYiVideoReturnInfo.class);
            end = returnInfo.getData().getEnd();
            Thread.sleep(5000);
        }
        saveJson.clear();
        saveJson.put("start", end - 20);
        saveJson.put("end", end);
        HttpUtil.postJson(postUrl, saveJson, cookie, heads);
    }


    /**
     * 将字符串的时间转成秒数
     *
     * @param s 字符串时间 06：03
     * @return 秒数
     */
    public static int getTime(String s) {
        int time = 0;
        try {
            String[] array = s.split(":");
            int i = array.length - 1;
            for (String a : array) {
                time += Math.pow(60, i) * Integer.parseInt(a);
                i--;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }

    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }


    //   String js = "document.getElementByClassName(\"mvp-play-progress\").setAttribute(\"style\",\"width: 97.5%;\")";
//        String js = "$('.mvp-play-progress').css('style','width: 20.5%;') ";
//
//        ((JavascriptExecutor) driver).executeScript(js);

    // https://www.cnblogs.com/du-hong/p/15337826.html
//        Thread.sleep(2000);
//        Actions action = new Actions(driver);
//     //   WebElement target = driver.findElement(By.className("mvp-play-progress"));
//      //  WebElement target = findElementByCssSelector(driver,"div[class='mvp-play-progress']",20);
//        WebElement target = findElementByCssSelector(driver,"div[class='mvp-progress-control']",20);
//     //   action.dragAndDropBy(target,1000,0);
//       // action.contextClick(target).moveByOffset(990,0).perform();
//
//     System.err.println("x:"+   target.getLocation().x);
//     System.err.println("y:"+   target.getLocation().y);
//
//     WebElement t1 = driver.findElement(By.cssSelector("button[class='mvp-play-rate-btn']"));
//        System.err.println("t1x:"+   t1.getLocation().x);
//        System.err.println("t1y:"+   t1.getLocation().y);
//
//        action.contextClick(target).moveToElement(t1).perform();
//
//        Thread.sleep(2000000);

}
